package com.youlu.campus.service.ad.impl;

import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.service.activity.ActivityTaskService;
import com.youlu.campus.service.activity.UserActivityTaskInfoService;
import com.youlu.campus.service.ad.UserAdsRecordService;
import com.youlu.campus.service.platform.PointPlatformConfigService;
import com.youlu.campus.service.ranking.UserActivityPointDetailService;
import com.youlu.campus.service.ranking.UserActivityPointRankingService;
import com.youlu.campus.service.ranking.UserPointRankingService;
import com.youlu.campus.service.visitor.UserPointsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
public class UserAdsRecordServiceImpl implements UserAdsRecordService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserPointsService userPointsService;
    @Autowired
    private PointPlatformConfigService pointPlatformConfigService;
    @Autowired
    private UserPointRankingService userPointRankingService;

    @Autowired
    private ActivityTaskService activityTaskService;

    @Autowired
    private UserActivityPointRankingService userActivityPointRankingService;

    @Autowired
    private UserActivityPointDetailService userActivityPointDetailService;

    @Override
    public UserAdsRecord create(UserAdsRecord req) {
        if (!StringUtils.isBlank(req.getId())) {
            req.setId(null);
        }
        if (!Objects.nonNull(req.getCreatedTime())) {
            req.setCreatedTime(new Date());
        }
        return mongoTemplate.insert(req);
    }

    @Override
    public boolean update(UserAdsRecord req) {
        Query query = new Query().addCriteria(Criteria.where("id").is(req.getId()));
        Update update = new Update();
        if (StringUtils.isNotBlank(req.getStatus())) {
            update.set("status", req.getStatus());
        }
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, UserAdsRecord.class);
        boolean re = updateResult.getModifiedCount() > 0 ? true : false;
        log.info(":>>> 更新广告记录:{} 结果:{}", req.getId(), re);
        return re;
    }

    @Override
    public UserAdsRecord findById(String id) {
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, UserAdsRecord.class);
    }

    @Override
    public UserAdsRecord find(String userId, Date dayTime, String platfrom, String appId) {
        if (StringUtils.isBlank(userId) || Objects.isNull(dayTime)) {
            log.error(":>>> 查询用户广告记录参数错误");
            throw new BusinessException("查询用户广告记录参数错误");
        }
        Query query = new Query().addCriteria(Criteria.where("userId").is(userId).and("dayTime")
                .is(dayTime).and("platfrom").is(platfrom).and("appId").is(appId));
        return mongoTemplate.findOne(query, UserAdsRecord.class);
    }

    @Override
    public UserAdsRecord startViewAd(String userId, String adId, String platfrom, String appId, Date date) {
        if (StringUtils.isBlank(userId) || Objects.isNull(date)) {
            log.error(":>>> 查询用户广告记录参数错误");
            throw new BusinessException("查询用户广告记录参数错误");
        }
//        Date dayTime = TimeUtils.getDayStartTime(date);
        Date dayTime = date;
        UserAdsRecord u = this.find(userId, dayTime, platfrom, appId);
        if (Objects.nonNull(u)) {
            return u;
        }
        u = new UserAdsRecord();
        u.setUserId(userId);
        u.setPlatfrom(platfrom);
        u.setAppId(appId);
        u.setStatus("doing");
        u.setDayTime(dayTime);
        u.setCreatedTime(date);
        u.setAdsInfoId(adId);
        return this.create(u);
    }

    @Override
    public UserActivityTaskAdsRecord startTaskViewAd(String activityId, String userId, String adId, String platform,
                                                     String appId) {
        ActivityTaskInfo activityTaskInfo = activityTaskService.find(activityId, TaskBizType.VIDEO);
        if (Objects.isNull(activityTaskInfo)) {
            log.error("【视频任务】该活动- > {}未有视频任务", activityId);
            return null;
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("activityId").is(activityId));
        query.addCriteria(Criteria.where("taskId").is(activityTaskInfo.getId()));
        query.addCriteria(Criteria.where("adsInfoId").is(adId));
        query.addCriteria(Criteria.where("status").is("doing"));
        Date now = new Date();
        Update update = new Update();
        boolean exists = this.mongoTemplate.exists(query, UserActivityTaskAdsRecord.class);
        if (!exists) {
            update.set("createdTime", now);
        }
        update.set("updatedTime", now);
        FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
        findAndModifyOptions.upsert(Boolean.TRUE);
        findAndModifyOptions.returnNew(Boolean.TRUE);
        return this.mongoTemplate.findAndModify(query, update, findAndModifyOptions, UserActivityTaskAdsRecord.class);
    }

    @Override
    public void endTaskViewAd(UserPO userPO, String id) {

        UserActivityTaskAdsRecord userActivityTaskAdsRecord = this.mongoTemplate.findById(id, UserActivityTaskAdsRecord.class);
        if(Objects.isNull(userActivityTaskAdsRecord)){
            log.error("【视频任务】该视频任务- > {} 不存在", id);
            return;
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        query.addCriteria(Criteria.where("status").is("doing"));
        Update update = new Update();
        update.set("status","done");
        UpdateResult updateResult = this.mongoTemplate.updateMulti(query,update, UserActivityTaskAdsRecord.class);
        if(updateResult.getModifiedCount()>0){
            ActivityTaskInfo activityTaskInfo = activityTaskService.findOne(userActivityTaskAdsRecord.getTaskId());
            if(Objects.isNull(activityTaskInfo)){
                return;
            }
            //增加活力值和活力值记录
            UserActivityPointDetail userActivityPointDetail = new UserActivityPointDetail();
            userActivityPointDetail.setAction("add");
            userActivityPointDetail.setActivityId(activityTaskInfo.getActivityId());
            userActivityPointDetail.setBizDesc("观看视频");
            userActivityPointDetail.setComments("观看视频" + activityTaskInfo.getPoints());
            userActivityPointDetail.setBizType("qa");
            userActivityPointDetail.setOptDate(new Date());
            userActivityPointDetail.setPoints(activityTaskInfo.getPoints().intValue());
            userActivityPointDetail.setUserId(userPO.getId());
            userActivityPointDetail.setUserPO(userPO);
            userActivityPointDetailService.create(userActivityPointDetail);

        }


    }

    @Override
    public boolean endViewAd(UserPO userPO, String id, String appId, String platform) {
        UserAdsRecord userAdsRecord = this.findById(id);
        if (Objects.isNull(userAdsRecord)) {
            log.error(":>>> 用户广告记录不存在:{}", id);
            throw new BusinessException("用户广告记录不存在");
        }
        log.info(":>>> 广告记录的状态:{},{}", id, userAdsRecord.getStatus());
        if ("done".equals(userAdsRecord.getStatus())) {
            return true;
        }
        Date date = new Date();
        userAdsRecord.setStatus("done");
        boolean re = this.update(userAdsRecord);
        if (re) {
            Integer point = pointPlatformConfigService.getPoint(appId, "ad");
            UserPointsDetail detail = new UserPointsDetail();
            detail.setUserId(userAdsRecord.getUserId());
            detail.setAction("add");
            detail.setBizDesc("观看视频");
            detail.setBizType("add");
            detail.setOptDate(date);
            detail.setPoints(point);
            detail.setComments("观看视频" + point + "积分");
            detail.setAppId(appId);
            detail.setPlatform(platform);
            userPointsService.addPoint(detail);
            userPointRankingService.updatePoint(userPO, "", point);
            return true;
        }
        return false;

    }
}
